import { PlusSquareOutlined } from '@ant-design/icons'
import type { InputRef } from 'antd'
import { Button, Input, Space, Tag } from 'antd'
import { TweenOneGroup } from 'rc-tween-one'
import React, { useEffect, useRef, useState } from 'react'

// 组件属性接口
type SignKeywordsAttributes<T> = Partial<{
  value: string
  onChange: (keywords: T) => void
}>
// 添加关键字组件
export default function SignKeywords({ value, onChange }: SignKeywordsAttributes<string>) {
  const [inputVisible, setInputVisible] = useState(false)
  const [keywords, setKeywords] = useState('')
  const [keywordsTags, setKeywordsTags] = useState<string[]>([])
  const inputRef = useRef<InputRef>(null)

  // 关键字字符串改变，重新设置关键字标签
  useEffect(() => {
    if (value) {
      setKeywordsTags(value.split(','))
    } else {
      setKeywordsTags([])
    }
  }, [value])

  // 添加关键字输入框状态可见时，自动获得焦点
  useEffect(() => {
    inputVisible && inputRef.current?.focus()
  }, [inputVisible])

  // 确认添加关键字
  const handleConfirmAddKeywords = () => {
    // 关键字不为空，才进行添加
    if (keywords.trim()) {
      // 将中文逗号、竖杠统一转成英文逗号
      let keywordsList = keywords.replace(/，|\|/g, ',').split(',')
      // 去除每一项首位空格
      keywordsList = keywordsList.map(item => item.trim())
      // 过滤出非空项以及不存在的项
      const filterKeywordsList = keywordsList.filter(value => value.trim() && keywordsTags.indexOf(value.trim()) === -1)
      onChange!([...keywordsTags, ...filterKeywordsList].toString())
    }
    setInputVisible(false)
    setKeywords('')
  }

  // 移除指定关键字标签
  const handleRemoveTag = (removedTag: string) => {
    const newTags = keywordsTags.filter(tag => tag !== removedTag)
    onChange!(newTags.toString())
  }

  return (
    <Space>
      {inputVisible ? (
        <Input
          ref={inputRef}
          type='text'
          style={{ width: 136 }}
          value={keywords}
          allowClear
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setKeywords(e.target.value)}
          onBlur={handleConfirmAddKeywords}
          onPressEnter={handleConfirmAddKeywords}
        />
      ) : (
        <Button icon={<PlusSquareOutlined />} onClick={() => setInputVisible(true)}>
          添加关键字
        </Button>
      )}
      <TweenOneGroup
        enter={{
          scale: 0.8,
          opacity: 0,
          type: 'from',
          duration: 100
        }}
        leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
        appear={false}
      >
        {keywordsTags.map(tag => (
          <span key={tag} style={{ display: 'inline-block' }}>
            <Tag
              closable
              className='m5'
              color='#2db7f5'
              onClose={e => {
                e.preventDefault()
                handleRemoveTag(tag)
              }}
            >
              {tag}
            </Tag>
          </span>
        ))}
      </TweenOneGroup>
    </Space>
  )
}
